package com.example.yskjproject.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.example.yskjproject.R;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.utils.EventBusUtil;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengMessageService;
import com.umeng.message.entity.UMessage;

import org.android.agoo.common.AgooConstants;
import org.json.JSONObject;

/**
 * 自定义接收并处理友盟推送消息的服务类
 */
public class MyCustomMessageService extends UmengMessageService {
    private static final String TAG = "MyCustomMessageService";

    @Override
    public void onMessage(Context context, Intent intent) {
        Log.i(TAG, "onMessage");
        try {
            String body = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
            UMessage message = new UMessage(new JSONObject(body));
            if (UMessage.DISPLAY_TYPE_NOTIFICATION.equals(message.display_type)) {
                //处理通知消息
                handleNotificationMessage(message);
            }
            if (message.display_type.equals(UMessage.DISPLAY_TYPE_CUSTOM)) {
                if (message.custom.contains("live_info_reload")) {
                    //TODO: 开发者实现：处理自定义透传消息
                    handleCustomMessage(message.text,context);
                    EventBusUtil.sendEvent(new EventMessage(EventContent.class_works_date));
                }
                if (message.custom.contains("pay_success")) {
                    EventBusUtil.sendEvent(new EventMessage(EventContent.pay_ok));
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 自定义消息
     * @param message
     */
    private void handleCustomMessage(String message,Context context) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel_id")
                .setContentTitle("您有新的消息")
                .setContentText(message)
                .setSmallIcon(R.mipmap.logo_icon) // 通知栏中的小图标
                .setAutoCancel(true); // 点击通知后自动清除
        Notification notification = builder.build();
        notificationManager.notify(1, notification); // 1是通知的ID，用于更新或取消通知

    }

    @TargetApi(Build.VERSION_CODES.O)
    private static NotificationChannel getDefaultMode(Context context) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = manager.getNotificationChannel("custom");
        if (channel != null) {
            return channel;
        }
        channel = new NotificationChannel("custom", "MyCustom", NotificationManager.IMPORTANCE_HIGH);
//        int raw = R.raw.umeng_push_notification_default_sound;
//        Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/raw/" + raw);
//        channel.setSound(uri, Notification.AUDIO_ATTRIBUTES_DEFAULT);
        channel.setShowBadge(true);
        channel.enableVibration(true);
        manager.createNotificationChannel(channel);
        return channel;
    }

    private void handleNotificationMessage(UMessage msg) {
        Notification.Builder builder;
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = getDefaultMode(this);
            builder = new Notification.Builder(this, channel.getId());
        } else {
            builder = new Notification.Builder(this);
        }
        builder.setContentTitle(msg.title)
                .setContentText(msg.text)
                .setTicker(msg.ticker)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.logo_icon)
                .setAutoCancel(true);
        Notification notification = builder.getNotification();
        manager.notify((int) SystemClock.elapsedRealtime(), notification);
        UTrack.getInstance().trackMsgShow(msg, notification);
    }

}
